package com.platform.qujia.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.platform.qujia.pojo.*;
import com.platform.qujia.service.*;
import com.platform.qujia.utils.CodeMsg;
import com.platform.qujia.utils.CryptUtil;
import com.platform.qujia.utils.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: zxy
 * @Date: 2023/10/22 11:51
 * @Description:
 */
@Service
@Slf4j
public class registrationReleaseServiceImpl implements RegistrationReleaseService {

    @Resource
    private CouponService couponService;

    @Resource
    private GradeService gradeService;
    @Resource
    private AppUserInfoService appUserInfoService;
    @Resource
    private AppUserSuperDetailService appUserSuperDetailService;
    @Resource
    private PayOrderService payOrderService;
    @Resource
    private EnterpriseService enterpriseService;


    @Override
    @Async
    public void registrationRelease(AppUserInfo appUserInfo) {
        //获取油企是否开启注册自动发券
        log.info("获取油企是否开启注册自动发券：油企id：{}",appUserInfo.getStationId());
        List<String> couponActivity = couponService.getCouponActivity(appUserInfo.getStationId());
        if (CollectionUtil.isNotEmpty(couponActivity)){
            log.info("获取发券方式：活动id：{}",couponActivity);
            for (String activeityId : couponActivity) {
                List<String> issueIdsByActivityId = couponService.getIssueIdsByActivityId(activeityId);
                if (CollectionUtil.isNotEmpty(issueIdsByActivityId)){
                    //调用发券接口
                    log.info("注册发券参数：{}，{}",appUserInfo.getMobilePhone(),issueIdsByActivityId);
                    drawCouponsForRecharge(appUserInfo.getMobilePhone(),issueIdsByActivityId,null,5,activeityId);
                }
            }

        }else {
            log.info("该油企没有注册发券活动");
        }
    }

    public String drawCouponsForRecharge(String mobilePhone,List<String> couponIssueIds,Integer ccsdId,Integer activityType,String couponActivity) {
        ResultData resultData = ResultData.error(CodeMsg.INSERT_FAIL);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        DrawCoupon drawCoupon = new DrawCoupon();
        drawCoupon.setMobilePhone(mobilePhone);
        drawCoupon.setCcsdId(ccsdId);
        drawCoupon.setRandomFlag(System.currentTimeMillis() + RandomStringUtils.randomNumeric(7));
        log.info( "; 手机号：" + mobilePhone + "; 优惠券IDs：" + couponIssueIds + "; 本次领取内随机数：" + drawCoupon.getRandomFlag());
        if ( StringUtils.isNotBlank(drawCoupon.getRandomFlag()) && StringUtils.isNotBlank(drawCoupon.getMobilePhone())) {
            if (activityType == 5){
                resultData = sendCoupon(drawCoupon,couponIssueIds,activityType,couponActivity);
            } else {
                resultData = sendCoupon(drawCoupon,couponIssueIds,activityType,"0");
            }
        }
        return gson.toJson(resultData);
    }

    public ResultData  sendCoupon(DrawCoupon drawCoupon,List<String> couponIssueIds,Integer activityType,String couponActivityId){
        ResultData resultData = null;
        Map<String, Object> activity = couponService.getActivityAllByActivityId(couponActivityId);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        List<CouponIssue> couponIssueAll = new ArrayList<>();

        Iterator<String> iterator = couponIssueIds.iterator();
        while (iterator.hasNext()) {
            String issueId = iterator.next();
            Map<String, Object> params = new HashMap<>();
            params.put("couponIssueId", issueId);
            List<CouponIssue> selectedCouponIssues = couponService.selectCouponListByCouponIssueId(params);
            int userIssueGiveCount = couponService.selectUserIssueGiveCount(CouponUserGiveCount.builder().mobilePhone(drawCoupon.getMobilePhone()).couponIssueId(issueId).build());
            if (!selectedCouponIssues.isEmpty() && userIssueGiveCount >= selectedCouponIssues.get(0).getGiveCount()) {
                iterator.remove();
            }
            if (selectedCouponIssues.isEmpty() || !selectedCouponIssues.get(0).getCouponIssueStatus().equals("1")) {
                iterator.remove();
            }
        }
        for (String issueId : couponIssueIds) {
            Map<String, Object> params = new HashMap<>();
            params.put("couponIssueId", issueId);

            List<CouponIssue> selectedCouponIssues = couponService.selectCouponListByCouponIssueId(params);
            couponIssueAll.addAll(selectedCouponIssues);
        }

        if (couponIssueAll.size() > 0) {
            int counter = 1; // 初始化计数器
            List<CouponTemplate> drawTemList = new ArrayList<>();
            for (CouponIssue couponIssueItem : couponIssueAll) {
                drawCoupon.setCouponIssueId(couponIssueItem.getCouponIssueId());

                drawCoupon.setCouTemIds(couponIssueItem.getCouponTemplateList().get(0).getCouponTemplateId().toString());
                // 生成后三位的字符串，保证至少有三位，不足的在前面补0
                String counterString = String.format("%03d", counter);

                // 获取原始的 randomFlag，即去掉后三位的部分
                String originalRandomFlag = drawCoupon.getRandomFlag().substring(0, drawCoupon.getRandomFlag().length() - 3);

                // 构建新的 randomFlag，将原始部分与后三位替换为循环数
                String newRandomFlag = originalRandomFlag + counterString;

                // 更新 drawCoupon 的 randomFlag
                drawCoupon.setRandomFlag(newRandomFlag);

                // 增加计数器
                counter++;
                //优惠券模板，优惠券领取方式；
                Map<String, Object> ciParam = new HashMap<>();
                ciParam.put("couponIssueId", couponIssueItem.getCouponIssueId());
                List<CouponIssue> couponIssues = couponService.selectCouponListByCouponIssueId(ciParam);
//            if(StringUtils.isNotBlank(drawCoupon.getOrdNo())){
//                couponIssues = couponIssues.stream().sorted(Comparator.comparing(CouponIssue::getThresholdAmt).reversed()).collect(Collectors.toList());
//            }
                if (null != couponIssues && !couponIssues.isEmpty()) {
                    CouponIssue couponIssue = couponIssues.get(0);  //该领取方式与该优惠券的模板
                    //结束时间在当前时间之后
                    if (couponIssue.getEndDate().after(new Date())) {
                        //开始时间在当前时间之前
                        if (couponIssue.getStartDate().before(new Date())) {
                            String couTemIds = drawCoupon.getCouTemIds();
                            String[] splitCouTemIds = couTemIds.split(","); //用户领取的优惠券
                            //用户一次领取的优惠券张数是否已超过该领取方式限定的一次领取张数
                            if (splitCouTemIds.length <= couponIssue.getGiveLimit()) {
                                //查询用户进入该领取方式的次数
                                int userIssueGiveCount = couponService.selectUserIssueGiveCount(CouponUserGiveCount.builder().mobilePhone(drawCoupon.getMobilePhone()).couponIssueId(drawCoupon.getCouponIssueId()).build());
                                CouponUser couponUser1 = couponService.selectUserIssueRedomMax(CouponUserGiveCount.builder().mobilePhone(drawCoupon.getMobilePhone()).couponIssueId(drawCoupon.getCouponIssueId()).build());
                                // 修改  这个应该是大于 ，当等于条件时，是可以继续领取的
                                if (userIssueGiveCount > couponIssue.getGiveCount()) {
                                    return ResultData.error(CodeMsg.COUPON_GIVE_COUNT_MAX);
                                } else if (userIssueGiveCount == couponIssue.getGiveCount() && couponUser1 != null && !couponUser1.getRandomFlag().equals(drawCoupon.getRandomFlag())) {
                                    return ResultData.error(CodeMsg.COUPON_GIVE_COUNT_MAX);
                                } else {
                                    AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(AppUserInfo.builder().mobilePhone(drawCoupon.getMobilePhone()).stationId(couponIssue.getEnterpriseId()).build());
                                    //该领取方式下可领取等级
                                    if ("plus".equals(couponIssue.getMemberCondition())) {
                                        //超级会员
                                        AppUserSuperDetail appUserSuperDetail = appUserSuperDetailService.selectAppUserSVIPInfoByCurrentTime(AppUserSuperDetail.builder()
                                                .enterpriseId(Long.valueOf(appUserInfo.getStationId()))
                                                .userId(Long.valueOf(appUserInfo.getUserId()))
                                                .build());
                                        if (null == appUserSuperDetail)
                                            return ResultData.error(CodeMsg.COUPON_ISSUE_SUPER_LEVEL);
                                    }
                                    if ("part".equals(couponIssue.getMemberCondition())) {
                                        //用户等级 表示那些等级普通会员可以领取
                                        List<Grade> gradeList = gradeService.selectUserGrade(Grade.builder()
                                                .enterpriseId(Long.valueOf(appUserInfo.getStationId()))
                                                .gradeGrowValue(appUserInfo.getGrowUpValue())
                                                .deleteFlag("0")
                                                .build());
//                                  TODO 如果前端置灰还有这种情况再做修改20230613
                                        if (!couponIssue.getMemberLevel().contains(gradeList.get(0).getGradeCode())) {
                                            return ResultData.error(CodeMsg.COUPON_ISSUE_LEVEL);
                                        }
                                        Map<String, Object> param = new HashMap<>();
                                        param.put("stationId", appUserInfo.getStationId());
                                        param.put("mobilePhone", drawCoupon.getMobilePhone());
                                        int i = payOrderService.selectUserOrderCount(param);
                                        if ("newUser".equals(couponIssue.getMemberTags())) {
                                            if (i > 0) return ResultData.error(CodeMsg.COUPON_NEW_USER);
                                        }
                                        if ("oldUser".equals(couponIssue.getMemberTags())) {
                                            if (i <= 0) return ResultData.error(CodeMsg.COUPON_OLD_USER);
                                        }
                                    }
                                    //1、查询用户当天的参与的次数
//                                CouponUserGiveCount cugc = couponService.selectCouponUserGiveCount(CouponUserGiveCount.builder().mobilePhone(drawCoupon.getMobilePhone()).couponIssueId(drawCoupon.getCouponIssueId()).randomFlag(drawCoupon.getRandomFlag()).build());
//                                if(null !=cugc){
//                                    //2、是否开启防作弊,防的是一天的进入页面的参与次数
//                                    if("0".equals(couponIssue.getAntiCheating()) && cugc.getIssueGiveCount() >= couponIssue.getCountOfDay())
//                                        return gson.toJson(ResultData.error(CodeMsg.MORE_DRAW_TODAY));
//                                    if("1".equals(couponIssue.getAntiCheating()) && cugc.getIssueGiveCount() == 1)
//                                        return gson.toJson(ResultData.error(CodeMsg.ONCE_DRAW_TODAY));
//                                }
                                    int count = couponService.selectCouponUserGiveCountByToday(CouponUserGiveCount.builder()
                                            .mobilePhone(drawCoupon.getMobilePhone())
                                            .couponIssueId(drawCoupon.getCouponIssueId())
                                            .curTimeSta(Date.from(LocalDate.now().atStartOfDay(ZoneOffset.ofHours(8)).toInstant()))
                                            .curTimeEnd(Date.from(LocalDate.now().plusDays(1).atStartOfDay(ZoneOffset.ofHours(8)).toInstant()))
                                            .build());
                                    if ("0".equals(couponIssue.getAntiCheating()) && count >= couponIssue.getCountOfDay())
                                        return ResultData.error(CodeMsg.MORE_DRAW_TODAY);
//                                if("1".equals(couponIssue.getAntiCheating()) && count >= 1)
//                                    return gson.toJson(ResultData.error(CodeMsg.ONCE_DRAW_TODAY));
//                                if("0".equals(couponIssue.getAntiMonthCheating())){
//                                    //如果 antiMonthCheating == 0 表示每月有限领次数
//                                    //Integer countOfMonth = couponIssue.getCountOfMonth();
//
//
//                                }


                                    List<CouponUser> saveCouUserList = new ArrayList<>();           //用户领取的优惠券；
                                    //用户能领取的优惠券
                                    List<Integer> updateTemIdsCountMap = new ArrayList<>();          //要更新的优惠券领取数量

                                    //优惠券模板列表
                                    List<CouponTemplate> couponTemplateList = couponIssues.get(0).getCouponTemplateList();
                                    if (null != couponTemplateList && couponTemplateList.size() > 0) {
                                        //获取用户同一个随机数已领取的优惠券
                                        List<CouponTemplate> temListByCouponUser = couponService.selectCouponTemListByCouponUser(CouponUser.builder()
                                                .randomFlag(drawCoupon.getRandomFlag()).couponIssueId(drawCoupon.getCouponIssueId()).mobilePhone(drawCoupon.getMobilePhone()).build());
                                        List<String> idsList = Arrays.asList(splitCouTemIds);
                                        for (CouponTemplate couponTemplate : couponTemplateList) {
                                            if (idsList.contains(couponTemplate.getCouponTemplateId().toString())) {
                                                if (couponTemplate.getCouponNum() > 0) {
                                                    if (null != temListByCouponUser && temListByCouponUser.size() > 0) {
                                                        List<Integer> collect = temListByCouponUser.stream().map(CouponTemplate::getCouponTemplateId).collect(Collectors.toList());
                                                        //如果同一个随机数已领取过，则返回前端 1 表示当前此优惠券已领取过；
                                                        if (collect.contains(couponTemplate.getCouponTemplateId())) {
                                                            couponTemplate.setCouDrawStatus("1");
                                                        } else {
                                                            Date startTime = new Date();     //开始时间
                                                            Date endTime = new Date();       //结束时间
                                                            //优惠券时间类型
                                                            switch (couponTemplate.getEffectiveTimeType()) {
                                                                case "1":   //固定时间
                                                                    //startTime = couponTemplate.getEffectiveTimeStart();
                                                                    endTime = couponTemplate.getEffectiveTimeEnd();
                                                                    break;
                                                                case "2":   //领取后有效天数
                                                                    startTime = new Date();
                                                                    Calendar instance = Calendar.getInstance();
                                                                    instance.setTime(new Date());
                                                                    instance.add(Calendar.DATE, couponTemplate.getEffectiveDayNum());
                                                                    endTime = instance.getTime();
                                                                    break;
                                                            }
                                                            Long ccsdId = drawCoupon.getCcsdId() != null ? drawCoupon.getCcsdId().longValue() : 0;
                                                            String activityName = "-";
                                                            if (activity.containsKey("activity_name") && activity.get("activity_name") != null) {
                                                                activityName = activity.get("activity_name").toString();
                                                            }
                                                            saveCouUserList.add(CouponUser.builder()
                                                                    .mobilePhone(drawCoupon.getMobilePhone())
                                                                    .couponIssueId(drawCoupon.getCouponIssueId())
                                                                    .couponTemplateId(couponTemplate.getCouponTemplateId())
                                                                    .couponIsUsed("0")
                                                                    .activityType(activityType)
                                                                    .activityName(activityName)
                                                                    .couponNo(CryptUtil.useMD5(couponIssue.getEnterpriseId() + Long.toString(System.currentTimeMillis()) + Math.round((Math.random() + 1) * 1000)))
                                                                    .enterpriseId(couponIssue.getEnterpriseId())
                                                                    .couponGetTime(startTime)
                                                                    .randomFlag(drawCoupon.getRandomFlag())
                                                                    .couponEffectiveTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime))
                                                                    .ccsdId(ccsdId)
                                                                    .build());
                                                            updateTemIdsCountMap.add(couponTemplate.getCouponTemplateId());
                                                            couponTemplate.setCouDrawStatus("1");
                                                        }
                                                    } else {
                                                        Date startTime = new Date();     //开始时间
                                                        Date endTime = new Date();       //结束时间
                                                        //优惠券时间类型
                                                        switch (couponTemplate.getEffectiveTimeType()) {
                                                            case "1":   //固定时间
                                                                //startTime = couponTemplate.getEffectiveTimeStart();
                                                                endTime = couponTemplate.getEffectiveTimeEnd();
                                                                break;
                                                            case "2":   //领取后有效天数
                                                                startTime = new Date();
                                                                Calendar instance = Calendar.getInstance();
                                                                instance.setTime(new Date());
                                                                instance.add(Calendar.DATE, couponTemplate.getEffectiveDayNum());
                                                                endTime = instance.getTime();
                                                                break;
                                                        }
                                                        Long ccsdId = drawCoupon.getCcsdId() != null ? drawCoupon.getCcsdId().longValue() : 0;
                                                        String activityName = "-";
                                                        if (activity.containsKey("activity_name") && activity.get("activity_name") != null) {
                                                            activityName = activity.get("activity_name").toString();
                                                        }
                                                        saveCouUserList.add(CouponUser.builder()
                                                                .mobilePhone(drawCoupon.getMobilePhone())
                                                                .couponIssueId(drawCoupon.getCouponIssueId())
                                                                .couponTemplateId(couponTemplate.getCouponTemplateId())
                                                                .couponIsUsed("0")
                                                                .activityType(activityType)
                                                                .activityName(activityName)
                                                                .couponNo(CryptUtil.useMD5(couponIssue.getEnterpriseId() + Long.toString(System.currentTimeMillis()) + Math.round((Math.random() + 1) * 1000)))
                                                                .enterpriseId(couponIssue.getEnterpriseId())
                                                                .couponGetTime(startTime)
                                                                .randomFlag(drawCoupon.getRandomFlag())
                                                                .couponEffectiveTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime))
                                                                .ccsdId(ccsdId)
                                                                .build());
                                                        updateTemIdsCountMap.add(couponTemplate.getCouponTemplateId());
                                                        couponTemplate.setCouDrawStatus("1");
                                                    }
                                                } else {
                                                    //代表此优惠券数量不足
                                                    couponTemplate.setCouDrawStatus("2");
                                                }
                                            } else {
                                                couponTemplate.setCouDrawStatus("0");
                                                //获取用户同一个随机数已领取的优惠券
                                                if (null != temListByCouponUser && temListByCouponUser.size() > 0) {
                                                    List<Integer> collect = temListByCouponUser.stream().map(CouponTemplate::getCouponTemplateId).collect(Collectors.toList());
                                                    //如果同一个随机数已领取过，则返回前端 1 表示当前此优惠券已领取过；
                                                    if (collect.contains(couponTemplate.getCouponTemplateId()))
                                                        couponTemplate.setCouDrawStatus("1");
                                                }
                                            }

                                            if (couponIssues != null && !couponIssues.isEmpty()) {
                                                CouponIssue firstCouponIssue = couponIssues.get(0);
                                                if (firstCouponIssue != null) {
                                                    List<Station> stationList = firstCouponIssue.getStaList();
                                                    if (stationList != null && !stationList.isEmpty()) {
                                                        List<String> stationNames = stationList
                                                                .stream()
                                                                .map(Station::getStationName)
                                                                .filter(Objects::nonNull) // 过滤掉空值
                                                                .collect(Collectors.toList());

                                                        if (!stationNames.isEmpty()) {
                                                            String concatenatedNames = String.join(";", stationNames);

                                                            firstCouponIssue.getCouponTemplateList().get(0).setCouponStaNames(concatenatedNames);
                                                        }
                                                    }
                                                }
                                            }


                                            drawTemList.add(couponTemplate);
                                        }
                                    }
                                    if (null != saveCouUserList && saveCouUserList.size() > 0) {
                                        CouponUserGiveCount cugc = couponService.selectCouponUserGiveCount(CouponUserGiveCount.builder().mobilePhone(drawCoupon.getMobilePhone()).couponIssueId(drawCoupon.getCouponIssueId()).randomFlag(drawCoupon.getRandomFlag()).build());
                                        if (null != cugc) {
                                            if (cugc.getIssueGiveCount() >= couponIssue.getGiveLimit()) {
                                                return ResultData.error(CodeMsg.COUPON_GIVE_LIMIT_MAX_NUM);
                                            } else {
                                                //用户分次领取后还可以领取的张数
                                                int i1 = couponIssue.getGiveLimit() - cugc.getIssueGiveCount();
                                                if (splitCouTemIds.length > i1) {
                                                    return ResultData.error(CodeMsg.COUPON_GIVE_LIMIT_MAX_NUM, "您已领取 " + cugc.getIssueGiveCount() + "张，还可领取 " + i1 + "张");
                                                } else {
                                                    //批量保存优惠券
                                                    if (!saveCouUserList.isEmpty()) {
                                                        CouponUser firstCouponUser = saveCouUserList.get(0);
                                                        saveCouUserList.clear();
                                                        saveCouUserList.add(firstCouponUser);
                                                    }
                                                    int i = couponService.saveBatchCouponUser(saveCouUserList);
                                                    log.info("批量保存的用户优惠券数量：" + i);
                                                    int y = couponService.updateBatchCouponTemplate(updateTemIdsCountMap);
                                                    log.info("批量更新的优惠券模板减少的模板优惠券数量：" + y);
                                                    couponService.updateCouponUserGiveCount(CouponUserGiveCount.builder()
                                                            .randomFlag(drawCoupon.getRandomFlag())
                                                            .issueGiveCount(saveCouUserList.size() + cugc.getIssueGiveCount())
                                                            .mobilePhone(drawCoupon.getMobilePhone())
                                                            .couponIssueId(drawCoupon.getCouponIssueId())
                                                            .build());
                                                }
                                            }
                                        } else {
                                            //批量保存优惠券
                                            if (!saveCouUserList.isEmpty()) {
                                                CouponUser firstCouponUser = saveCouUserList.get(0);
                                                saveCouUserList.clear();
                                                saveCouUserList.add(firstCouponUser);
                                            }
                                            int i = couponService.saveBatchCouponUser(saveCouUserList);
                                            log.info("批量保存的用户优惠券数量：" + i);
                                            int y = couponService.updateBatchCouponTemplate(updateTemIdsCountMap);
                                            log.info("批量更新的优惠券模板减少的模板优惠券数量：" + y);
                                            couponService.insertCouponUserGiveCount(CouponUserGiveCount.builder()
                                                    .mobilePhone(drawCoupon.getMobilePhone())
                                                    .couponIssueId(drawCoupon.getCouponIssueId())
                                                    .createTime(new Date())
                                                    .issueGiveCount(saveCouUserList.size())
                                                    .enterpriseId(appUserInfo.getStationId())
                                                    .randomFlag(drawCoupon.getRandomFlag())
                                                    .build());
                                        }
                                        if ("plus".equals(couponIssue.getMemberCondition())) {
                                            //超级会员
                                            AppUserSuperDetail appUserSuperDetail = appUserSuperDetailService.selectAppUserSVIPInfoByCurrentTime(AppUserSuperDetail.builder()
                                                    .enterpriseId(Long.valueOf(appUserInfo.getStationId()))
                                                    .userId(Long.valueOf(appUserInfo.getUserId()))
                                                    .build());
                                            if (null == appUserSuperDetail)
                                                return ResultData.error(CodeMsg.COUPON_ISSUE_SUPER_LEVEL);
                                            if (StringUtils.isNotBlank(appUserInfo.getBlogOpenid())) {
                                                Enterprise enterprise = enterpriseService.selectEnterpriseInfo(couponIssue.getEnterpriseId());
                                                if (null != enterprise) {
                                                    couponService.pushWxGzhInitiativeCouponInfo(enterprise, saveCouUserList.size(), appUserInfo);
                                                }
                                            }
                                        }
                                        if ("part".equals(couponIssue.getMemberCondition())) {
                                            //用户等级 表示那些等级普通会员可以领取
                                            List<Grade> gradeList = gradeService.selectUserGrade(Grade.builder()
                                                    .enterpriseId(Long.valueOf(appUserInfo.getStationId()))
                                                    .gradeGrowValue(appUserInfo.getGrowUpValue())
                                                    .deleteFlag("0")
                                                    .build());
                                            if (!couponIssue.getMemberLevel().contains(gradeList.get(0).getGradeCode())) {
                                                return ResultData.error(CodeMsg.COUPON_ISSUE_LEVEL);
                                            }
                                            Map<String, Object> param = new HashMap<>();
                                            param.put("stationId", appUserInfo.getStationId());
                                            param.put("mobilePhone", drawCoupon.getMobilePhone());
                                            int i = payOrderService.selectUserOrderCount(param);
                                            if ("newUser".equals(couponIssue.getMemberTags())) {
                                                if (i > 0)
                                                    return ResultData.error(CodeMsg.COUPON_NEW_USER);
                                            }
                                            if ("oldUser".equals(couponIssue.getMemberTags())) {
                                                if (i <= 0)
                                                    return ResultData.error(CodeMsg.COUPON_OLD_USER);
                                            }
                                            if ("all".equals(couponIssue.getMemberCondition())) {
                                                if (StringUtils.isNotBlank(appUserInfo.getBlogOpenid())) {
                                                    Enterprise enterprise = enterpriseService.selectEnterpriseInfo(couponIssue.getEnterpriseId());
                                                    if (null != enterprise) {
                                                        couponService.pushWxGzhInitiativeCouponInfo(enterprise, saveCouUserList.size(), appUserInfo);
                                                    }
                                                }
                                            }
                                        }
                                        if (StringUtils.isNotBlank(appUserInfo.getBlogOpenid())) {
                                            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(couponIssue.getEnterpriseId());
                                            if (null != enterprise) {
                                                couponService.pushWxGzhInitiativeCouponInfo(enterprise, saveCouUserList.size(), appUserInfo);
                                            }
                                        }
                                    }
                                    resultData = ResultData.success(drawTemList);
                                }
                            } else {
                                resultData = ResultData.error(CodeMsg.COUPON_GIVE_LIMIT_MAX);
                            }
                        } else {
                            resultData = ResultData.error(CodeMsg.NOT_GIVE_COUPON_TIME);    //当前时间小于该领取方式的开始时间，表示该领取方式还未开始；
                        }
                    } else {
                        resultData = ResultData.error(CodeMsg.MORE_COUPON_TIME_END); //当前时间大于该领取方式结束时间；表示该领取方式已关闭
                    }
                } else {
                    resultData = ResultData.error(CodeMsg.NO_COUPON_ISSUE); //没有表示该领取方式所对应的优惠券没有
                }
            }
        } else {
            resultData = ResultData.error(CodeMsg.NO_ISSUE); //必传参数不能为空
        }
        return resultData;

    }
}
